<?php

class AttachmentController extends Controller
{
		
	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}
	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Attachment('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Attachment']))
			$model->attributes=$_GET['Attachment'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Attachment::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='mem-group-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}

	/**
	 * get ajax uploaded files.
	 */
	public function actionGetAjax()
	{
		//$zat_id  = !empty($_GET['zat_id'])?$_GET['zat_id']:'';取附件ID
        //$model=Attachment::model()->findByPk($zat_id);
		$model=new Attachment();
	    $memberid  = !empty($_GET['memberid'])?$_GET['memberid']:'';	        
	    $tmpFile   = empty($_FILES['imgFile'])?CUploadedFile::getInstanceByName('image'):CUploadedFile::getInstanceByName('imgFile');
		$Directroy = Yii::app()->params['uploadPath'];		
		//创建文件存放路径
	    $y         = date('Y');
	    $m         = date('m');
	    $d         = date('d');
	    $Directroy = $Directroy."/";
	    $pathd = $Directroy.$y."/".$m."/".$d."/";	    	     
	    Tool::makedir(dirname(Yii::app()->BasePath).$pathd); //创建文件夹	
		if(is_object($tmpFile) && get_class($tmpFile)==='CUploadedFile'){
            $filename               = time().rand(11111,99999);
            $ext                    = $tmpFile->extensionName;//上传文件的扩展名
            $upfiletype             = Tool::check_file_type($tmpFile->name,Yii::app()->params['upfiletype']);//判断是否充许上传的附件;
            
            if($upfiletype==''){            	
            	$str = json_encode(
            			array(
            			'upfile'=>array(
            				'errors' => 1,
            				'msg'=>'上传的文件类型不正确!'
            				)
            			)
            	);//类型错误执行
            	echo $str;
            	exit;
            }
            //取系统配置，如无系统配置，取默认19M
            $fileMaxSize = F::setting('upload_max_fileSize');
            $fileMaxSize = empty($fileMaxSize)?"2000000":$fileMaxSize;
            if($tmpFile->size > $fileMaxSize){
            	$str = json_encode(
            			array(
            			'upfile'=>array(
            				'errors' => 1,
            				'msg'=>'上传的文件大于系统限制!'
            				)
            			)
            	);//文件大小错误执行
            	echo $str;
            	exit;
            }
            $checkext               = Tool::check_file_type($tmpFile->name,'|jpg|gif|png|bmp|');//判断类型是否符合                  
            if($checkext!=''){
            	$big                    = $pathd . $filename . '_600.' . $ext; //310缩略图  
	            $small                  = $pathd . $filename . '_310.' . $ext; //310缩略图
	            $thumb                  = $pathd . $filename . '_100.' . $ext; //100缩略图    
	            $model->zat_thumb       = $thumb; //缩略图
            }    
            $uploadfile             = $pathd . $filename . '.' . $ext; //保存的路径
            $model->zat_url         = $pathd . $filename . '.' . $ext;//重新赋值 
            if(!empty($memberid)){
            	$model->zm_id           = $memberid;           //会员ID            	
            }else{
            /*	if(isset(Yii::app()->user->userid) && Yii::app()->user->userid){
            		$model->zm_id           = Yii::app()->user->userid;           //会员ID
            	}  */    
            	$model->zm_id       =   Company::model()->getCmpUserId();	//商家会员ID，如果不是商家，则不空
            }             
            $model->zat_file_name   = $filename . '.' . $ext;               //文件名称           
            $model->zat_title       = $tmpFile->name;                       //文件标题
            $model->zat_description = $tmpFile->name;                       //文件描述
            $model->zat_file_type   = $tmpFile->type;                       //文件类型
            $model->zat_file_size   = $tmpFile->size;                       //文件大小
            if($checkext!=''){
            	$model->zat_image       = 2;                                //是图像
        	}else{
        		$model->zat_image       = 1;                                //不是图像
        	}
            $model->zat_ip          = Yii::app()->request->userHostAddress; //上传IP
            //print_r($uploadfile);            
        }        
        if($model->save()){
            $tmpFile->saveAs(dirname(Yii::app()->BasePath).$uploadfile);//保存到服务器
	   /*     if($checkext!=''){     
		        $img = Yii::app()->image->load(dirname(Yii::app()->BasePath).$uploadfile);
		        $img->resize(600,600)->quality(85);
				$img->save(dirname(Yii::app()->BasePath).$big);//生成600缩略图
				$img->resize(310,310)->quality(85);
				$img->save(dirname(Yii::app()->BasePath).$small);//生成310缩略图
				$img->resize(100,100)->quality(85);
				$img->save(dirname(Yii::app()->BasePath).$thumb);//生成100缩略图				
			} */
			if($checkext!=''){           
		        $str = json_encode(
		        	array(
		        		'upfile'=>array(
		        			'errors' => 0,
		        			'zat_id' => Yii::app()->db->getLastInsertID(), //取插ID
		        			'file' => $uploadfile,//原文件
		        			'small' => $small,//310缩略图
		        			'thumb' => $thumb,//100缩略图
		        		),
	        			//用于kEditor
	        			'error' => 0,
	        			'url' => $uploadfile,
		        	)
		        );
		    }else{
		    	$str = json_encode(
		        	array(
		        		'upfile'=>array(
		        			'errors' => 0,
		        			'zat_id' => Yii::app()->db->getLastInsertID(),
		        			'file' => $uploadfile,	
		        		),
	        			//用于kEditor
	        			'error' => 0,
	        			'url' => $uploadfile,
		        	)
		        );
		    }
	        echo $str;exit;
        }
			    
	}
	
	/**
	 * 替换图片
	 */
	public function actionReplace()
	{
	
		$zat_id  = (int)$_GET['id'];//取附件ID
		$model=Attachment::model()->findByPk($zat_id);
		 
		$tmpFile   = empty($_FILES['imgFile'])?CUploadedFile::getInstanceByName('image'):CUploadedFile::getInstanceByName('imgFile');

		if(is_object($tmpFile) && get_class($tmpFile)==='CUploadedFile'){
			$upfiletype             = Tool::check_file_type($tmpFile->name,Yii::app()->params['upfiletype']);//判断是否充许上传的附件;
	
			if($upfiletype==''){
				$str = json_encode(
						array(
								'upfile'=>array(
										'errors' => 1,
										'msg'=>'上传的文件类型不正确!'
								)
						)
				);//类型错误执行
				echo $str;
				exit;
			}
			if($tmpFile->size > 20000000){
				$str = json_encode(
						array(
								'upfile'=>array(
										'errors' => 1,
										'msg'=>'请上传小于2M的文件!'
								)
						)
				);//文件大小错误执行
				echo $str;
				exit;
			}
			$checkext               = Tool::check_file_type($tmpFile->name,'|jpg|gif|png|bmp|');//判断类型是否符合
			if($checkext!=''){
				$big                    = str_replace('_100.','_600.',$model->zat_thumb); //310缩略图
				$small                  = str_replace('_100.','_310.',$model->zat_thumb); //310缩略图
				$thumb                  = $model->zat_thumb; //100缩略图
			}
			$uploadfile             = $model->zat_url; //保存的路径

			$tmpFile->saveAs(dirname(Yii::app()->BasePath).$uploadfile);//保存到服务器
		/*	if($checkext!=''){
				$img = Yii::app()->image->load(dirname(Yii::app()->BasePath).$uploadfile);
				$img->resize(600,600)->quality(85);
				$img->save(dirname(Yii::app()->BasePath).$big);//生成600缩略图
				$img->resize(310,310)->quality(85);
				$img->save(dirname(Yii::app()->BasePath).$small);//生成310缩略图
				$img->resize(100,100)->quality(85);
				$img->save(dirname(Yii::app()->BasePath).$thumb);//生成100缩略图
			}*/
			if($checkext!=''){
				$str = json_encode(
						array(
								'upfile'=>array(
										'errors' => 0,
										'zat_id' => Yii::app()->db->getLastInsertID(), //取插ID
										'file' => $uploadfile,//原文件
										'small' => $small,//310缩略图
										'thumb' => $thumb,//100缩略图
								),
						)
				);
			}else{
				$str = json_encode(
						array(
								'upfile'=>array(
										'errors' => 0,
										'zat_id' => Yii::app()->db->getLastInsertID(),
										'file' => $uploadfile,
								),
						)
				);
			}
			echo $str;exit;
		}
		 
	}
	
	public function actionDelAjax()
	{
		$zat_id  = !empty($_GET['zat_id'])?$_GET['zat_id']:'';//取附件ID
        $model = $this->loadModel($zat_id);
        Tool::delUpload($model->zat_url);
        $model->delete();
	}
	
	public function actionDelImg()
	{
		$img_url  = !empty($_GET['url'])?$_GET['url']:'';//取附件ID
		$model = Attachment::model()->findByAttributes(array('zat_url'=>$img_url));
		
		//存在订单商品中的图片不能删除
		$criteria=new CDbCriteria;
		$criteria->compare('zop_pic',$model->zat_url);
		if(OrdProduct::model()->exists($criteria)){
			return;
		}
		
		//删除相册记录
		$criteria=new CDbCriteria;
		$criteria->compare('zat_id',$model->zat_id);
		Albums::model()->deleteAll($criteria);
		
		Tool::delUpload($img_url);
		$model->delete();
	}
}

